import datetime

from django.shortcuts import render, HttpResponse, redirect
from django import forms

from app01 import models
from app01.utils.forms import LoginFrom, NoteBookModelForm, NoteBookEditModelForm,NoteModelForm
from app01.utils.yanzhengma import getPicture

# Create your views here.


# 笔记本
def notebook_list(request):
    uid = request.session["info"]["id"]
    queryset = models.NoteBook.objects.filter(user=uid)

    return render(request, 'notebook_list.html', {"queryset": queryset})


def notebook_add(request):
    if request.method == "GET":
        form = NoteBookModelForm()
        return render(request, 'notebook_add.html', {"form": form})

    kk = {"user": request.session["info"]["id"],
          "title": request.POST["title"],
          "create_time": datetime.datetime.now()}
    form = NoteBookModelForm(data=kk)
    # form.cleaned_data["create_time"] = datetime.datetime.now()
    # form.cleaned_data["user"] = request.session["info"]["id"]
    if form.is_valid():
        form.save()
        return redirect("/notebook/")

    return render(request, 'notebook_add.html', {"form": form})


def notebook_edit(request, book_id):
    obj = models.NoteBook.objects.filter(id=book_id).first()

    if request.method == "GET":
        form = NoteBookModelForm(instance=obj)
        return render(request, "notebook_edit.html", {"form": form})

    form = NoteBookEditModelForm(data=request.POST, instance=obj)
    if form.is_valid():
        form.save()
        return redirect("/notebook/")


def notebook_delete(request, book_id):
    models.NoteBook.objects.filter(id=book_id).first().delete()
    return redirect('/notebook/')


# 笔记
def note_list(request, book_id):
    queryset = models.Note.objects.filter(notebook_id=book_id)
    return render(request, 'note_list.html', {"queryset": queryset, "book_id": book_id})


def note(request, note_id):
    queryset = models.Note.objects.filter(id=note_id).first()

    return render(request, 'note.html', {"note": queryset})


def note_add(request, notebook_id):
    if request.method == "GET":
        form = NoteBookModelForm()
        return render(request, 'note_add.html', {"form": form})

    print(request.session["info"])
    kk = {"notebook": notebook_id,
          "title": request.POST["title"],
          "content": request.POST["content"],
          "create_time": datetime.datetime.now()}
    form = NoteModelForm(data=kk)
    # form.cleaned_data["create_time"] = datetime.datetime.now()
    # form.cleaned_data["user"] = request.session["info"]["id"]
    if form.is_valid():
        form.save()
        return redirect("/note_list/{}".format(notebook_id))

    return render(request, 'note_add.html', {"form": form})

def note_edit(request, note_id):
    obj = models.Note.objects.filter(id=note_id).first()

    if request.method == "GET":
        form = NoteBookModelForm(instance=obj)
        return render(request, "notebook_add.html", {"form": form})

    form = NoteBookModelForm(data=request.POST, instance=obj)
    if form.is_valid():
        form.save()
        return redirect("/notebook/{}/".format(request.session["info"]["id"]))


def note_delete(request, note_id):
    obj = models.Note.objects.filter(id=note_id).first()
    book_id = obj.notebook_id
    obj.delete()
    return redirect("/note_list/{}".format(book_id))

# 登录
def login(request):
    if request.method == "GET":
        form = LoginFrom()
        code = getPicture()
        request.session["verify"] = code
        request.session.set_expiry(60)
        return render(request, 'login.html', {"form": form})

    form = LoginFrom(data=request.POST)
    if form.is_valid():
        verify = form.cleaned_data.pop("verify")
        a = request.session.get("verify", "")
        if verify != a:
            form.add_error("verify", "验证码错误")
            code = getPicture()
            request.session["verify"] = code
            request.session.set_expiry(60)
            return render(request, 'login.html', {"form": form})

        user_info = models.User.objects.filter(**form.cleaned_data).first()
        if user_info:
            request.session["info"] = {'id': user_info.id, 'name': user_info.name, 'book_id': ""}
            request.session.set_expiry(60 * 60 * 24 * 7)
            return redirect('/notebook/')
        else:
            form.add_error("password", "用户或密码错误")
            return render(request, "login.html", {"form": form})
    return render(request, 'login.html', {"form": form})


def logout(request):
    request.session.clear()
    return redirect('/login/')
